﻿using M_Quality.API.Application.Command.ReinspectionCommand;
using M_Quality.Domain;
using M_Quality.Repository;
using M_Quality.Repository.Interface;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace M_Quality.API.Application.CommandHandler.ReinspectionCommandHandler
{
    /// <summary>
    /// 复检不合格销毁
    /// </summary>
    public class XiaohuiReinspectionCommandHandler : IRequestHandler<XiaohuiReinspectionCommand, int>
    {
        private readonly MyDbcontract _myDbcontract;
        /// <summary>
        /// 复检接口
        /// </summary>
        private readonly IReinspectionRepository _Reinspectionrepository;
        /// <summary>
        /// 原料质检接口
        /// </summary>
        private readonly IRawMaterialQualityRepository _rawMaterialQualityRepository;
        public XiaohuiReinspectionCommandHandler(IReinspectionRepository reinspectionrepository, IRawMaterialQualityRepository rawMaterialQualityRepository, MyDbcontract myDbcontract)
        {
            _Reinspectionrepository = reinspectionrepository;
            _rawMaterialQualityRepository = rawMaterialQualityRepository;
            _myDbcontract = myDbcontract;
        }
        public async Task<int> Handle(XiaohuiReinspectionCommand request, CancellationToken cancellationToken)
        {
            var ss = _myDbcontract.Database.CreateExecutionStrategy();
            return await ss.ExecuteAsync(async () =>
            {
                using(var tran = _myDbcontract.Database.BeginTransaction())
                {
                    try
                    {
                        var res = await _Reinspectionrepository.GetModelAsync(request.ReinspectionId);
                        res.IsDeleted = true;
                        await _Reinspectionrepository.UpdateAsync(res);

                        var ter = await _rawMaterialQualityRepository.GetModelAsync(request.RawMaterialQualityId);
                        ter.QualityNum = ter.QualityNum - ter.UnqualifiedQuantity;
                        ter.UnqualifiedQuantity = 0;
                        await _rawMaterialQualityRepository.UpdateAsync(ter);
                       
                        tran.Commit();
                        return 1;
                    }
                    catch (Exception)
                    {
                        tran.Rollback();//回滚事务
                        throw;
                    }
                }

            });
        }
    }
}
